package com.example.echoewish.repository.network.service;

import android.content.Intent;

import com.example.echoewish.econstant.Constant;
import com.example.echoewish.pojo.Chat;
import com.example.echoewish.util.EchoWishApplication;
import com.example.echoewish.util.LogUtil;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.nio.ByteBuffer;

public class ChatService extends WebSocketClient {

    public ChatService(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        new LogUtil().i(LogUtil.CHAT_TAG,"连接成功");
    }

    @Override
    public void onMessage(String message) {
        try {
            JSONObject result = new JSONObject(message);
            Chat chat=new Chat();
            chat.content=result.getString("content");
            chat.time=result.getString("time");
            sendMessageBroadcast(chat);
            new LogUtil().i(LogUtil.CHAT_TAG,"发来信息:"+message);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        new LogUtil().i(LogUtil.CHAT_TAG,"连接关闭");
    }

    @Override
    public void onError(Exception ex) {
        new LogUtil().w(LogUtil.CHAT_TAG,"出现错误"+ex);
    }

    //通过广播传播信息（解决 层耦合问题）
    private void sendMessageBroadcast(Chat chat){
        if (chat!=null){
            Intent intent = new Intent();
            intent.setAction(Constant.ACTION_RECEIVE_MESSAGE);
            intent.putExtra(Constant.KEY_RECEIVED_DATA_CONTENT,chat.content);
            intent.putExtra(Constant.KEY_RECEIVED_DATA_TIME,chat.time);
            EchoWishApplication.getContext().sendOrderedBroadcast(intent,null);
        }
    }
}
